<?php
namespace app\controller;

use think\Request;
use app\BaseController;
use app\model\User;
use app\model\UserToken;
use app\model\OperationLog;
use app\model\SystemConfig;
use Firebase\JWT\JWT;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Config;
use think\facade\View;
use app\model\IpLimit;
use app\model\LoginFailure;
use app\model\Feedback;
use app\model\ReminderSend;

class UserController extends BaseController
{
    private $verificationCodeExpireTime = 86400; // 验证码有效期24小时

    /**
     * 记录操作日志
     */
    public static function logOperation($userId, $type, $desc, Request $request)
    {
        OperationLog::create([
            'user_id' => $userId,
            'operation_type' => $type,
            'operation_desc' => $desc,
            'operation_time' => time(),
            'ip_address' => $request->ip(),
            'user_agent' => $request->header('user-agent')
        ]);
    }

    /**
     * IP调用限制检查
     * @param string $ip IP地址
     * @param string $apiType 接口类型
     * @param int $maxCount 最大调用次数
     * @return bool|array 成功返回true，失败返回错误信息
     */
    private function checkIpLimit($ip, $apiType, $maxCount = 10)
    {
        $today = date('Y-m-d');
        
        // 查找或创建今天的记录
        $record = IpLimit::where([
            'ip_address' => $ip,
            'api_type' => $apiType,
            'date' => $today
        ])->find();

        if ($record) {
            // 检查是否超过限制
            if ($record->count >= $maxCount) {
                return [
                    'status' => 429,
                    'message' => '您今天的操作次数已达上限，请明天再试',
                    'remaining_time' => strtotime('tomorrow') - time()
                ];
            }
            
            // 更新计数
            $record->count = $record->count + 1;
            $record->save();
        } else {
            // 创建新记录
            IpLimit::create([
                'ip_address' => $ip,
                'api_type' => $apiType,
                'count' => 1,
                'date' => $today
            ]);
        }

        return true;
    }

    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        // IP限制检查
        $ipCheck = $this->checkIpLimit($request->ip(), 'register');
        if ($ipCheck !== true) {
            return json($ipCheck);
        }

        $data = $request->post();
        
        if (empty($data['username']) || empty($data['password']) || empty($data['email'])) {
            return json(['status' => 400, 'message' => '用户名、密码和邮箱不能为空']);
        }

        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            return json(['status' => 400, 'message' => '邮箱格式不正确']);
        }

        // 检查用户名和邮箱是否已存在
        if (User::where('username', $data['username'])->whereOr('email', $data['email'])->find()) {
            return json(['status' => 400, 'message' => '用户名或邮箱已存在']);
        }

        // 生成验证码
        $verificationCode = substr(md5(uniqid(rand(), true)), 0, 6);
        
        // 密码加密（使用 PASSWORD_DEFAULT 算法）
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);

        try {
            // 创建用户
            $user = new User;
            $user->username = $data['username'];
            $user->password = $hashedPassword;  // 直接赋值加密后的密码
            $user->email = $data['email'];
            $user->is_verified = 0;
            $user->verification_code = $verificationCode;
            $user->verification_time = time();
            $user->save();

            // 发送验证码邮件，传入用户ID
            $mailService = new \app\service\MailService();
            $mailService->sendVerificationCode($user->id, $user->email, $verificationCode);

            // 记录操作日志
            $this->logOperation($user->id, 'register', '用户注册', $request);

            return json([
                'status' => 200,
                'message' => '注册成功，验证码已发送至您的邮箱，请查收并完成验证。'
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            \think\facade\Log::error('注册失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '注册失败，请稍后重试']);
        }
    }

    /**
     * 更新密钥
     */
    public function updateReminderKey(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        // 生成新密钥（加入用户ID）
        $newKey = md5(uniqid(rand(), true) . $user->id);
        
        // 更新用户密钥
        $user->reminder_key = $newKey;
        $user->save();

        // 记录操作日志
        $this->logOperation($user->id, 'update_key', '更新提醒密钥', $request);

        return json([
            'status' => 200,
            'message' => '密钥更新成功',
            'reminder_key' => $newKey
        ]);
    }

    /**
     * 邮箱验证
     */
    public function verifyEmail(Request $request)
    {
        $userId = $request->get('user_id');
        $code = $request->get('code');

        $user = User::where('id', $userId)
            ->where('verification_code', $code)
            ->find();

        if (!$user) {
            return json(['status' => 400, 'message' => '验证失败，验证码错误']);
        }

        // 检查验证码是否过期（24小时）
        if (time() - $user->verification_time > $this->verificationCodeExpireTime) {
            return json(['status' => 400, 'message' => '验证码已过期，请重新获取']);
        }

        // 生成初始密（加入用户ID）
        $reminderKey = md5(uniqid(rand(), true) . $userId);

        // 更新用户状态
        $user->is_verified = 1;
        $user->verification_code = null;
        $user->verification_time = null;
        $user->reminder_key = $reminderKey;
        $user->save();

        // 记录操作日志
        $this->logOperation($user->id, 'verify_email', '邮箱验证', $request);

        return json(['status' => 200, 'message' => '邮箱验证成功，您可以登录系统了。']);
    }

    /**
     * 检查登录安全限制
     * @param string $email 邮箱
     * @param string $ip IP地址
     * @return array|true
     */
    private function checkLoginSecurity($email, $ip)
    {
        $now = time();
        $fiveMinutesAgo = $now - 300;  // 5分钟前
        $halfHourAgo = $now - 1800;    // 30分钟前
        $oneDayAgo = $now - 86400;     // 24小时前

        // 检查IP是否被锁定
        $ipFailures = LoginFailure::where('ip_address', $ip)
            ->where('attempt_time', '>', $oneDayAgo)
            ->count();
        
        if ($ipFailures >= 30) {
            return [
                'status' => 403,
                'message' => '由于多次登录失败，此IP已被临时锁定，请24小时后再试'
            ];
        }

        // 检查账号是否被锁定
        $accountFailures = LoginFailure::where('email', $email)
            ->where('attempt_time', '>', $oneDayAgo)
            ->count();
        
        if ($accountFailures >= 20) {
            return [
                'status' => 403,
                'message' => '由于多次登录失败，此账号已被锁定24小时'
            ];
        }

        // 检查账号是否被临时��定
        $recentFailures = LoginFailure::where('email', $email)
            ->where('attempt_time', '>', $fiveMinutesAgo)
            ->count();
        
        if ($recentFailures >= 10) {
            return [
                'status' => 403,
                'message' => '由于多次登录失败，此账号已被临时锁定30分钟'
            ];
        }

        return true;
    }

    /**
     * 记录登录失败并发送警告邮件
     */
    private function recordLoginFailure($email, $ip, $userId = null)
    {
        LoginFailure::create([
            'user_id' => $userId,
            'email' => $email,
            'ip_address' => $ip,
            'attempt_time' => time()
        ]);

        // 检查是否需要发送警告邮件
        $this->checkAndSendWarningEmail($email, $ip);
    }

    /**
     * 检查并发送警告邮件
     */
    private function checkAndSendWarningEmail($email, $ip)
    {
        $now = time();
        $fiveMinutesAgo = $now - 300;
        $halfHourAgo = $now - 1800;

        $recentFailures = LoginFailure::where('email', $email)
            ->where('attempt_time', '>', $fiveMinutesAgo)
            ->count();

        $halfHourFailures = LoginFailure::where('email', $email)
            ->where('attempt_time', '>', $halfHourAgo)
            ->count();

        if ($recentFailures == 10 || $halfHourFailures == 20) {
            // 发送警告邮件
            $mailService = new \app\service\MailService();
            $mailService->sendSecurityWarningEmail($email, $ip, $halfHourFailures >= 20);
        }
    }

    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        try {
            $email = $request->post('email');
            $password = $request->post('password');
            $ip = $request->ip();

            // 安全检查
            $securityCheck = $this->checkLoginSecurity($email, $ip);
            if ($securityCheck !== true) {
                return json($securityCheck);
            }

            // 查找用户
            $user = User::where('email', $email)->find();
            
            // 验证失败，记录并返回错误
            if (!$user || !password_verify($password, $user->getData('password'))) {
                $this->recordLoginFailure($email, $ip, $user ? $user->id : null);
                return json(['status' => 400, 'message' => '邮箱或密码错误']);
            }

            if (!$user->is_verified) {
                return json(['status' => 400, 'message' => '请先验证邮箱']);
            }

            // 登录成功，软删除失败记录
            LoginFailure::where('email', $email)
                ->select()
                ->each(function($record) {
                    $record->delete();  // 使用模型的软删除方法
                });

            // 生成新的访问令牌
            $token = $this->generateToken($user);

            // 记录操作日志
            $this->logOperation($user->id, 'login', '用户登录', $request);

            return json([
                'status' => 200,
                'message' => '登录成功',
                'token' => $token
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('登录失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '登录失败，请稍后重试']);
        }
    }

    /**
     * 生成新的令牌
     */
    private function generateToken($user)
    {
        $expiredAt = time() + Config::get('jwt.expire_time');

        // 先将用户之前的token标记为已撤销
        UserToken::where('user_id', $user->id)
            ->where('is_revoked', 0)
            ->where('delete_time', null)
            ->update([
                'is_revoked' => 1,
                'delete_time' => time()
            ]);

        // 生成JWT
        $token = JWT::encode([
            'iss' => 'reminder_system',
            'iat' => time(),
            'exp' => $expiredAt,
            'user_id' => $user->id
        ], Config::get('jwt.key'), 'HS256');

        // 记录新令牌
        UserToken::create([
            'user_id' => $user->id,
            'token' => $token,
            'created_at' => time(),
            'expired_at' => $expiredAt,
            'is_revoked' => 0
        ]);

        return $token;
    }

    /**
     * 获取提醒密钥
     */
    public function getReminderKey(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        return json([
            'status' => 200,
            'message' => '提醒密钥获取成功',
            'reminder_key' => $user->reminder_key
        ]);
    }


    /**
     * 获取当前日期时间
     */
    private function getCurrentDateTime()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 从请求中获取用户信息
     */
    public static function getUserFromToken(Request $request)
    {
        // 优先从 header 获取 token
        $token = $request->header('Authorization');
        
        // 如果 header 中没有，则尝试从 GET 参数获取
        if (!$token) {
            $token = $request->param('authorization');
        }
        
        if (!$token) {
            return null;
        }

        try {
            // 如果是 Bearer token 格式，去掉前缀
            if (strpos($token, 'Bearer ') === 0) {
                $token = str_replace('Bearer ', '', $token);
            }
            
            // 检查令牌是否存在且有效
            $tokenRecord = UserToken::where('token', $token)
                ->where('is_revoked', 0)
                ->where('expired_at', '>', time())
                ->find();

            if (!$tokenRecord) {
                return null;
            }

            return User::find($tokenRecord->user_id);
        } catch (\Exception $e) {
            \think\facade\Log::error('Token验证失败：' . $e->getMessage());
            return null;
        }
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $oldPassword = $request->post('old_password');
        $newPassword = $request->post('new_password');
        $confirmPassword = $request->post('confirm_password');

        // 验证参数
        if (empty($oldPassword) || empty($newPassword) || empty($confirmPassword)) {
            return json(['status' => 400, 'message' => '所有密码字段都不能为空']);
        }

        // 验证新密码长度
        if (strlen($newPassword) < 6) {
            return json(['status' => 400, 'message' => '新密码长度不能小于6位']);
        }

        // 验证新密码一致性
        if ($newPassword !== $confirmPassword) {
            return json(['status' => 400, 'message' => '两次输入的新密码不一致']);
        }

        // 验证原密码
        if (!password_verify($oldPassword, $user->getData('password'))) {
            return json(['status' => 400, 'message' => '原密码错误']);
        }

        // 更新密码
        $user->password = password_hash($newPassword, PASSWORD_DEFAULT);
        $user->save();

        // 记录操作日志
        $this->logOperation($user->id, 'change_password', '修改密码', $request);

        return json(['status' => 200, 'message' => '密码修改成功']);
    }

    /**
     * 发送重置密码验证码
     */
    public function sendResetCode(Request $request)
    {
        // IP限制检查（一天最多5次）
        $ipCheck = $this->checkIpLimit($request->ip(), 'reset_password', 5);
        if ($ipCheck !== true) {
            return json($ipCheck);
        }
        $email = $request->param('email');
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return json(['status' => 400, 'message' => '请提供有效的邮箱地址']);
        }

        $user = User::where('email', $email)->find();
        if (!$user) {
            return json(['status' => 400, 'message' => '该邮箱未注册']);
        }

        try {
            // 生成重置验证码
            $resetCode = substr(md5(uniqid(rand(), true)), 0, 6);
            
            // 更新用户验证码信息
            $user->verification_code = $resetCode;
            $user->verification_time = time();
            $user->save();

            // 发送重置密码邮件
            $mailService = new \app\service\MailService();
            $mailService->sendResetPasswordEmail($user->email, $user->id, $resetCode);

            return json([
                'status' => 200,
                'message' => '重置密码验证码已发送到您的邮箱'
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('发送重置密码邮件失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '发送重置密码邮件失败，请稍后重试']);
        }
    }

    /**
     * 重置密码
     */
    public function resetPassword(Request $request)
    {
        $userId = $request->post('user_id');
        $email = $request->post('email');
        $code = $request->post('code');
        $newPassword = $request->post('new_password');
        $confirmPassword = $request->post('confirm_password');

        // 验证参数
        if (empty($code) || empty($newPassword) || empty($confirmPassword)) {
            return json(['status' => 400, 'message' => '验证码和密码不能为空']);
        }

        if (empty($userId) && empty($email)) {
            return json(['status' => 400, 'message' => '用户ID或邮箱地址必须提供一个']);
        }

        // 验证新密码长度
        if (strlen($newPassword) < 6) {
            return json(['status' => 400, 'message' => '新密码长度不能小于6位']);
        }

        // 验证新密码一致性
        if ($newPassword !== $confirmPassword) {
            return json(['status' => 400, 'message' => '两次输入的新密码不一致']);
        }

        // 查找用户
        $query = User::where('verification_code', $code);
        if ($userId) {
            $query->where('id', $userId);
        } else {
            $query->where('email', $email);
        }
        $user = $query->find();

        if (!$user) {
            return json(['status' => 400, 'message' => '验证码错误']);
        }

        // 检查验证码是否过期（24小时）
        if (time() - $user->verification_time > $this->verificationCodeExpireTime) {
            return json(['status' => 400, 'message' => '验证码已过期，请重新获取']);
        }

        try {
            // 开启事务
            \think\facade\Db::startTrans();

            // 更新密码
            $user->password = password_hash($newPassword, PASSWORD_DEFAULT);
            $user->verification_code = null;
            $user->verification_time = null;
            $user->save();

            // 清除登录失败记录（软删除）
            LoginFailure::where('email', $user->email)
                ->select()
                ->each(function($record) {
                    $record->delete();
                });

            // 记录操作日志
            $this->logOperation($user->id, 'reset_password', '重置密码并解除账号锁定', $request);

            // 提交事务
            \think\facade\Db::commit();

            return json([
                'status' => 200, 
                'message' => '密码重置成功，账号已解除锁定，请使用新密码登录'
            ]);

        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            \think\facade\Log::error('密码重置失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '密码重置失败，请稍后重试']);
        }
    }

    /**
     * 发送重置密码邮件
     */
    private function sendResetEmail($email, $userId, $resetCode)
    {
        try {
            $mailService = new \app\service\MailService();
            return $mailService->sendResetPasswordEmail($email, $userId, $resetCode);
        } catch (\Exception $e) {
            throw new \Exception('重置密码邮件发送失败：' . $e->getMessage());
        }
    }

    /**
     * 显示重置密码页面
     */
    public function resetPasswordPage(Request $request)
    {
        $userId = $request->param('user_id');
        $code = $request->param('code');

        if (empty($userId) || empty($code)) {
            return '<h1>无效的重置链接</h1>';
        }

        // 查找用户
        $user = User::where('id', $userId)
            ->where('verification_code', $code)
            ->find();

        if (!$user) {
            return '<h1>验证码错误或已失效</h1>';
        }

        // 检查验证码是否过期（24小时）
        if (time() - $user->verification_time > $this->verificationCodeExpireTime) {
            return '<h1>验证码已过期，请重新获取</h1>';
        }

        // 获取系统名称
        $siteName = SystemConfig::getConfig('site_name', '知更开放平台');

        View::assign([
            'user_id' => $userId,
            'code' => $code,
            'email' => $user->email,
            'site_name' => $siteName
        ]);

        return View::fetch('user/reset_password');
    }

    /**
     * 显示重置密码页面并发送重置邮件
     */
    public function toResetPasswordPage(Request $request)
    {
        $email = $request->param('email');
        if (empty($email)) {
            return '<h1>邮箱地址不能为空</h1>';
        }

        // 发送重置密码邮件
        $this->sendResetCode($request);

        View::assign('email', $email);
        return View::fetch('user/to_reset_password');
    }

    /**
     * 重新发送验证码
     */
    public function resendVerificationCode(Request $request)
    {
        $email = $request->param('email');
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return json(['status' => 400, 'message' => '请提供有效的邮箱地址']);
        }

        $user = User::where('email', $email)->find();
        if (!$user) {
            return json(['status' => 400, 'message' => '该邮箱未注册']);
        }

        if ($user->is_verified) {
            return json(['status' => 400, 'message' => '该邮箱已验证']);
        }

        try {
            // 生成新的验证码
            $verificationCode = substr(md5(uniqid(rand(), true)), 0, 6);
            
            // 更新用户验证码信息
            $user->verification_code = $verificationCode;
            $user->verification_time = time();
            $user->save();

            // 发送验证码邮件，传入用户ID
            $mailService = new \app\service\MailService();
            $mailService->sendVerificationCode($user->id, $user->email, $verificationCode);

            return json([
                'status' => 200,
                'message' => '验证码已重新发送到您的邮箱'
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('重新发送验证码失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '发送验证码失败，请稍后重试']);
        }
    }

    /**
     * 获取用户信息
     */
    public function info(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            // 获取用户未完成的提醒数量
            $unfinishedReminders = \app\model\Reminder::where('user_id', $user->id)
                ->where('is_finished', 0)
                ->where('is_disabled', 0)
                ->count();

            // 获取用户笔记数量
            $notesCount = \app\model\Note::where('user_id', $user->id)
                ->count();

            // 获取用户项目数量
            $projectsCount = \app\model\Project::where('user_id', $user->id)
                ->where('status', \app\model\Project::STATUS_ONGOING)
                ->count();

            return json([
                'status' => 200,
                'data' => [
                    'user' => [
                        'id' => $user->id,
                        'username' => $user->username,
                        'email' => $user->email,
                        'is_verified' => $user->is_verified,
                        'reminder_key' => $user->reminder_key,
                        'created_at' => date('Y-m-d H:i:s', $user->created_at),
                        'last_login_at' => $user->last_login_at ? date('Y-m-d H:i:s', $user->last_login_at) : null,
                        'last_login_ip' => $user->last_login_ip
                    ],
                    'statistics' => [
                        'unfinished_reminders' => $unfinishedReminders,
                        'notes_count' => $notesCount,
                        'active_projects' => $projectsCount
                    ],
                    'permissions' => [
                        'can_create_project' => true,
                        'can_create_reminder' => true,
                        'can_use_ai' => true
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('获取用户信息失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取用户信息失败']);
        }
    }

    /**
     * 提交意见反馈
     */
    public function submitFeedback(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['title']) || empty($data['content'])) {
            return json(['status' => 400, 'message' => '标题和内容不能为空']);
        }

        try {
            $feedback = new Feedback;
            $feedback->user_id = $user->id;
            $feedback->title = $data['title'];
            $feedback->content = $data['content'];
            $feedback->type = $data['type'] ?? Feedback::TYPE_SUGGESTION;
            $feedback->status = Feedback::STATUS_PENDING;
            $feedback->save();

            // 记录操作日志
            $this->logOperation($user->id, 'submit_feedback', "提交意见反馈：{$data['title']}", $request);

            return json([
                'status' => 200,
                'message' => '感谢您的反馈，我们会认真处理',
                'data' => [
                    'feedback_id' => $feedback->id
                ]
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('提交意见反馈失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '提交失败，请稍后重试']);
        }
    }

    /**
     * 获取我的反馈列表
     */
    public function myFeedbacks(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        try {
            $feedbacks = Feedback::where('user_id', $user->id)
                ->with(['replyUser' => function($query) {
                    $query->field('id,username');
                }])
                ->order('created_at', 'desc')
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page
                ]);

            return json([
                'status' => 200,
                'data' => [
                    'total' => $feedbacks->total(),
                    'current_page' => $feedbacks->currentPage(),
                    'last_page' => $feedbacks->lastPage(),
                    'feedbacks' => $feedbacks->items()
                ]
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('获取反馈列表失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取失败，请稍后重试']);
        }
    }

    /**
     * 获取提醒发送记录
     */
    public function reminderSendHistory(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminderId = $request->param('reminder_id');
        $sendType = $request->param('send_type');
        $sendStatus = $request->param('send_status');
        $startTime = $request->param('start_time');
        $endTime = $request->param('end_time');
        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        try {
            $query = ReminderSend::where('user_id', $user->id);

            // 应用筛选条件
            if ($reminderId) {
                $query->where('reminder_id', $reminderId);
            }
            if ($sendType) {
                $query->where('send_type', $sendType);
            }
            if ($sendStatus) {
                $query->where('send_status', $sendStatus);
            }
            if ($startTime) {
                $query->where('send_time', '>=', strtotime($startTime));
            }
            if ($endTime) {
                $query->where('send_time', '<=', strtotime($endTime));
            }

            // 关联提醒信息
            $query->with(['reminder' => function($query) {
                $query->field('id,title,due_date');
            }]);

            // 获取分页数据
            $records = $query->order('send_time', 'desc')
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page
                ]);
            // return json($records);

            // 格式化数据
            $items = array_map(function($record) {
                return [
                    'id' => $record->id,
                    'reminder_id' => $record->reminder_id,
                    'reminder_title' => $record->reminder->title ?? '已删除的提醒',
                    'reminder_due_date' => $record->reminder->due_date ?? null,
                    'send_type' => $record->send_type,
                    'send_type_text' => $this->getSendTypeText($record->send_type),
                    'send_status' => $record->send_status,
                    'send_status_text' => $record->send_status == ReminderSend::STATUS_SUCCESS ? '成功' : '失败',
                    'error_message' => $record->error_message,
                    'send_time' => date('Y-m-d H:i:s', $record->send_time)
                ];
            }, $records->items());

            return json([
                'status' => 200,
                'data' => [
                    'total' => $records->total(),
                    'current_page' => $records->currentPage(),
                    'last_page' => $records->lastPage(),
                    'records' => $items
                ]
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('获取提醒发送记录失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取记录失败，请稍后重试']);
        }
    }

    /**
     * 获取发送类型文本
     */
    private function getSendTypeText($type)
    {
        $types = [
            ReminderSend::TYPE_EMAIL => '邮件',
            ReminderSend::TYPE_MESSAGE => '站内信',
            ReminderSend::TYPE_OTHER => '其他'
        ];
        return $types[$type] ?? '未知';
    }
} 